import { getUserListApi, logout, getInfo } from '@/api/acl'



const getDefaultState = () => {
  return {
    
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },

  //存储token
  SET_TOKEN: (state, token) => {
    state.token = token
    setToken(token)//存储token
  },
  SET_USERINFO: (state, data) => {
    state.userinfo = data
  }
}

const actions = {
  // 登录
  async login({ commit }, userInfo) {
    try {
      let res = await login(userInfo)
      if (res.code == 20000) {
        commit('SET_TOKEN', res.data.token)
      } else {
        return Promise.reject(res.message)
      }
    } catch (error) {
      return Promise.reject(error)
    }
  },
  //获取用户信息
  async getInfo({ commit }) {
    try {
      let res = await getInfo()
      if (res.code == 20000) {
        commit('SET_USERINFO', res.data)
      } else {
        return Promise.reject(res.message)
      }
    } catch (error) {
      return Promise.reject(error)
    }


  },

  //退出登录
  async logout({commit}) {
    try {
     await logout()
      removeToken()
      resetRouter()
      commit('RESET_STATE')
    } catch (error) {
      return Promise.reject(error)
    }
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

